package com.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.crmeb.core.exception.CrmebException;
import com.utils.vo.IdCardUtilsVo;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class IdCardUtils {
    @Autowired
    private RestTemplateUtil restTemplateUtil;
    
    @Value("${aliyun.card.enable}")
	private Boolean enable;
    @Value("${aliyun.card.url}")
    private String url;
    @Value("${aliyun.card.appcode}")
    private String appcode;

    /**
     * 身份证二要素认证
     * @author daigb
     * @date:  2022-10-26 15:07
     */
	public void checkIdCard(String name, String idNo) {
		if(!enable) {
	    	log.info("--------------- 姓名: {}, 证件号: {}, 当前环境不校验二要素 ---------------", idNo, name);
			return;
		}
		
		if(StringUtils.isBlank(idNo) || StringUtils.isBlank(name)) {
            throw new CrmebException("身份信息不能为空");
		}
		
	    Map<String, String> headers = new HashMap<String, String>();
	    headers.put("Authorization", "APPCODE " + appcode);
	 
	    MultiValueMap<String, Object> bodys = new LinkedMultiValueMap<String, Object>();
	    bodys.add("name", name);
	    bodys.add("idCardNo", idNo);

    	String result = restTemplateUtil.postMapData(url, bodys, headers, MediaType.APPLICATION_FORM_URLENCODED);
    	log.info("--------------- 姓名: {}, 证件号: {}, 身份证实名认证返回结果:{} ---------------", idNo, name, result);
        IdCardUtilsVo idCardUtilsVo = JSONObject.parseObject(result, IdCardUtilsVo.class);
        if(idCardUtilsVo.getCode() != 200){
            throw new CrmebException(idCardUtilsVo.getMsg());
        }else {
            if(!Objects.equals(idCardUtilsVo.getData().getResult(),0)){
                if(Objects.equals(idCardUtilsVo.getData().getDesc(),"不一致")){
                    throw new CrmebException("姓名与身份证号码匹配不一致");
                }else if(Objects.equals(idCardUtilsVo.getData().getDesc(),"无记录")){
                    throw new CrmebException("身份证号码错误");
                }else {
                    throw new CrmebException(idCardUtilsVo.getData().getDesc());
                }
            }
        }
	}

}
